Skip to main content

Deep Copy of Arrays

deep_copy(input: Number | any[] ) : Number | any[]

param input - the number or JS array your want a deep copy of. I.e. a new reference.

returns: Number | any[] - a replicate of the input but with a different reference.

This function is very useful for many functions that need to modify parameters or other JS arrays. Since there is no way of cloning a JS array in a deep way, we have to write a way ourselves. For example, even if you created a new array and copied all the items from the original array to the new array, the new array would still have the reference to the original array causing issues when modifying the new array and trying to access the old array - because the old array would now be updated too. This prevents that.

Effectively, if you have a JS array that is a independent, non-shallow copy of another array, simply call deep_copy(array_to_copy). Then when you modify this new, independent array, it will not interfere in any manner with array_to_copy.